package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 移动端用户管理
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     */
    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user,HttpSession session){
        //1.获取用户手机号
        String phone = user.getPhone();
        //2.生成随机的验证码（工具类）
        String code = RandomStringUtils.random(4, false, true);
        //3.发送短信，并且将验证码存入session中
        System.out.println("phone:"+phone+"验证码验证码验证码;"+code);
        //session.setAttribute(phone,code);

        //将验证码存入redis并设置有效期
        redisTemplate.opsForValue().set(phone,code, 5,TimeUnit.MINUTES);


        return R.success("发送成功");

    }

    /**
     *登录
     *
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        String phone =(String) map.get("phone");

        //1.比较验证码是否正确（提交的和session,no!no!no!改为从redis中获取)
        String code1 =(String) map.get("code");

        //String code2 =(String) session.getAttribute(phone);
        String code2 = (String) redisTemplate.opsForValue().get(phone);

        if(!StringUtils.equals(code1,code2)){
            //登录失败
            return R.error("验证码错误");
        }
            //登录成功1.将user存入session2.返回数据
            //根据phone查询用户id
        User user = userService.lambdaQuery()
            .eq(User::getPhone, phone)
            .one();
        if(user == null){
            //新用户
            User user1 = new User();
            user1.setPhone(phone);
            user1.setStatus(1);
            userService.save(user1);
        }
        session.setAttribute("user",user.getId());

        //及时删除redis中的验证码
        redisTemplate.delete(phone);

        return R.success(user);


    }

}
